import { fileURLToPath, URL } from 'node:url'
import { defineConfig, splitVendorChunkPlugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import OptimizationPersist from 'vite-plugin-optimize-persist'
import PkgConfig from 'vite-plugin-package-config'

import postCssPxToRem from 'postcss-pxtorem'
import autoprefixer from 'autoprefixer'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import nodePolyfills from 'rollup-plugin-polyfill-node'
import { customHtmlPlugin } from './vite.html.plugin.js'
import viteCompression from 'vite-plugin-compression'
import legacy from '@vitejs/plugin-legacy'

export default ({ mode }) =>
  defineConfig({
    define: {
      'process.env': process.env
    },

    // ✅ 支持 BigInt 等新语法
    esbuild: {
      target: 'esnext',
      supported: {
        bigint: true
      }
    },

    publicDir: 'public',
    base: '/', // 防止线上资源 404
    clearScreen: true,

    plugins: [
      vue(),
      legacy({
        targets: ['defaults', 'not IE 11']
      }),
      PkgConfig(),
      OptimizationPersist(),
      nodePolyfills({ include: ['buffer'] }),
      Components({
        dts: true,
        resolvers: [VantResolver()]
      }),
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia']
      }),
      splitVendorChunkPlugin(),
      customHtmlPlugin(mode),

      /**
       * ✅ 启用 Gzip 压缩
       */
      viteCompression({
        verbose: true,             // 输出压缩日志
        disable: false,            // 启用 gzip 压缩
        threshold: 10240,          // 仅压缩 >10KB 的文件
        algorithm: 'gzip',
        ext: '.gz',
        deleteOriginFile: false    // 不删除原文件
      }),

      /**
       * ✅ 启用 Brotli 压缩（兼容现代浏览器）
       */
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'brotliCompress',
        ext: '.br',
        deleteOriginFile: false
      })
    ],

    server: {
      host: true,
      https: false,
      cors: true,
      open: false,
      port: 9000,
      strictPort: false,
      hmr: true
    },

    css: {
      postcss: {
        plugins: [
          autoprefixer(),
          postCssPxToRem({
            rootValue: 37.5,
            unitToConvert: 'px',
            viewportWidth: 375,
            unitPrecision: 6,
            viewportUnit: 'vw',
            fontViewportUnit: 'vw',
            exclude: [/node_modules/],
            minPixelValue: 1,
            propList: ['*'],
            selectorBlackList: ['px-'],
            mediaQuery: false,
            replace: true,
            landscape: false
          })
        ]
      }
    },

    resolve: {
      alias: {
        'vue-i18n': 'vue-i18n/dist/vue-i18n.esm-bundler.js',
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },

    json: {
      namedExports: false,
      stringify: false
    },

    build: {
      target: 'esnext',
      outDir: 'dist',
      assetsInlineLimit: 500,
      cssCodeSplit: true,
      sourcemap: false,
      minify: 'terser',
      terserOptions: {
        mangle: true,
        toplevel: true,
        module: true,
        compress: {
          drop_console: true,
          drop_debugger: true
        },
        format: {
          comments: false
        }
      },
      write: true,
      emptyOutDir: true,
      brotliSize: true,
      chunkSizeWarningLimit: 500,
      reportCompressedSize: false
    },

    rollupOptions: {
      preserveEntrySignatures: false,
      output: {
        minify: true,
        compact: true,
        minifyInternalExports: true,
        chunkFileNames: '[name]-[hash].js',
        assetFileNames: 'assets/[name]-[hash][extname]',
        manualChunks: (id) => {
          if (id.includes('node_modules')) {
            return 'vendor'
          } else if (id.includes('/src/views/')) {
            return 'views'
          }
        }
      }
    }
  })
